package job

import (
	"gitee.com/chicken-c/go-learn/webook/pkg/logger"
	"github.com/robfig/cron/v3"
	"time"
)

type CronJobBuild struct {
	l logger.Logger
}

func NewCronJobBuild(l logger.Logger) *CronJobBuild {
	return &CronJobBuild{l: l}
}

// 这里传入的参数Job就是我们定义的接口
func (b *CronJobBuild) Build(job Job) cron.Job {
	name := job.Name()
	return cron.FuncJob(func() {
		now := time.Now()
		b.l.Info("开始执行任务", logger.Field{
			Key: "name",
			Val: name,
		})

		err := job.Run()
		end := time.Now().Sub(now).String()
		if err != nil {
			b.l.Error("任务执行失败", logger.Field{
				Key: "name",
				Val: name,
			}, logger.Field{
				Key: "error",
				Val: err,
			})
		} else {
			b.l.Info("任务执行完成", logger.Field{
				Key: "name",
				Val: name,
			}, logger.Field{
				Key: "总共用时",
				Val: end,
			})
		}
	})
}
